from cryptography.fernet import Fernet
from meiduo_mall.settings import FERNET_KEY_SECRET, SECRET_KEY

from itsdangerous import URLSafeTimedSerializer

# ENCRYPT_KEY = Fernet.generate_key()


def encrypt(content):
    """
    将字符串进行加密
    """
    fernet = Fernet(FERNET_KEY_SECRET)
    content = fernet.encrypt(content.encode()).decode()
    return content


def decrypt(content):
    """
    将字符串进行解密
    """
    fernet = Fernet(FERNET_KEY_SECRET)
    return fernet.decrypt(content.encode()).decode()


def get_serializer(secret_key=SECRET_KEY):
    return URLSafeTimedSerializer(SECRET_KEY, salt='myapp')


def encrypt_dict(data):
    """
    将字典进行加密,加密内部带有事件戳.
    """
    serializer = get_serializer()
    token = serializer.dumps(data)
    return token


def decrypt_dict(token, max_age=3600):
    """
    将字典进行解密, 可以传递指定超时时间， 如果超过，则抛异常，否则返回正确的解密字典;
    """
    serializer = get_serializer()
    try:
        data = serializer.loads(token, max_age=max_age)
        return data
    except Exception as e:
        print(f'Token verification failed:{e}')
        return None


if __name__ == '__main__':
    content = encrypt("hello123affeeffe,33434feefsaef3434bbbaefefsfs")
    print(content)
    src = decrypt(content)
    print(src)
    print(decrypt("gAAAAABm99Pc3RFJdIGa2DHQMRiCex_hfYc4X1rL5GrLLilY9kElfXRR8k6qbD6N7cf2tWLJCJRWXFZ1U_INirqckcS2VLVA6g6D_0KtaixbC_BEYZtPf4KDFwCKyd1GWmGJGkZMaWiO"))
